package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Stack;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import elitech.vietnam.myfashion.LoginActivity;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.dialog.ConnectionErrorDialog;
import elitech.vietnam.myfashion.dialog.OkCancelWarnningDialog;
import elitech.vietnam.myfashion.dialog.WarningDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.entites.ProductDetail;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.DetailAdapter;
import elitech.vietnam.myfashion.utilities.Utilities;

public class NewProductDetailView extends RelativeLayout implements OnClickListener {

	private MainActivity mContext;
	private Button mBtnSend;
	private EditText mEdComment;
	private ListView mListView;
	private DetailAdapter mDetailAdapter;
	private LinearLayout mLayoutLikes;
	private ImageView mMain_cart;
	private TextView mTxtLike, mTxtTitle;
	private boolean isProcessing = false;
	private Product mProduct;
	private int mProductID = -1;
	private String mTitle;
	private FooterDetailView mFooter;
	private HeaderDetailView mHeader;
	private RecommendGroupView mRecommend;
	private Stack<Product> mStack = new Stack<Product>();

	public NewProductDetailView(MainActivity context, Product product) {
		super(context);
		this.mContext = context;
		this.mProduct = product;

		LoadLayout();
	}

	public NewProductDetailView(MainActivity context, int product) {
		super(context);
		this.mContext = context;
		this.mProductID = product;
		LoadLayout();
	}

	public void ChangeProduct(Product product) {
		mStack.push(mProduct);
		mDetailAdapter.clear();
		mDetailAdapter.isRecommend = false;
		mDetailAdapter.notifyDataSetChanged();
		mProduct = product;
		mListView.removeHeaderView(mHeader);
		mListView.removeFooterView(mFooter);
		RefreshLayout(false);
	}

	public boolean PopBack() {
		if (mStack.size() == 0)
			return true;
		else {
			mProduct = mStack.pop();
			mDetailAdapter.clear();
			mDetailAdapter.isRecommend = false;
			mDetailAdapter.notifyDataSetChanged();
			mListView.removeHeaderView(mHeader);
			mListView.removeFooterView(mFooter);
			RefreshLayout(false);
			return false;
		}
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		// mContext.mBtnCart.setVisibility(View.VISIBLE);
	}

	private void LoadLayout() {
		new CallServiceTask() {
			private View mMainMenu;

			public void work() {
				int accountID = (mContext.mUser == null) ? -1 : mContext.mUser.Id;
				if (mProduct == null)
					try {
						mProduct = service.getProductByID(mProductID, accountID);
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
			};

			protected void onPostExecute(Void result) {
				if (mProduct == null) {
					mContext.onBackPressed();
					return;
				}
				if (mContext.getLocale().equals(Locale.ENGLISH))
					mTitle = mProduct.CategoryNameEN;
				else if (mContext.getLocale().equals(Locale.KOREA))
					mTitle = mProduct.CategoryNameKR;
				else
					mTitle = mProduct.CategoryNameVN;

				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				if (inflater != null) {
					inflater.inflate(R.layout.newproductdetail, NewProductDetailView.this);
				}

				mEdComment = (EditText) findViewById(R.id.detail_txtComment);
				mBtnSend = (Button) findViewById(R.id.detail_btnSend);
				mLayoutLikes = (LinearLayout) findViewById(R.id.detail_layBtnLike);
				mTxtLike = (TextView) findViewById(R.id.detail_txtLikes);
				mTxtTitle = (TextView) findViewById(R.id.main_title);
				mListView = (ListView) findViewById(R.id.detail_listView);
				mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
				mMain_cart = (ImageView) findViewById(R.id.main_cart);

				mMainMenu.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						mContext.callMenu();
					}
				});

				mMain_cart.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						mContext.callCart();
					}
				});

				mTxtTitle.setText(mTitle);

				mDetailAdapter = new DetailAdapter(mContext, R.id.detail_listView, 0, mProduct);

				mHeader = new HeaderDetailView(mContext, mProduct);
				mRecommend = new RecommendGroupView(mContext, mProduct);
				mFooter = new FooterDetailView(mContext, mProduct);

				mListView.addHeaderView(mHeader);
				mListView.addFooterView(mRecommend);
				mListView.addFooterView(mFooter);

				mListView.setAdapter(mDetailAdapter);

				mBtnSend.setOnClickListener(NewProductDetailView.this);
				mLayoutLikes.setOnClickListener(NewProductDetailView.this);

				mTxtLike.setText(mProduct.Likes + "");
				if (mProduct.Liked())
					mLayoutLikes.setBackgroundResource(R.drawable.liked);

				if (mProduct.DetailList.size() == 0)
					GetDetail();

			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void GetDetail() {
		new CallServiceTask() {
			private ArrayList<ProductDetail> rs = new ArrayList<ProductDetail>();

			public void work() {
				try {
					rs = service.getProductDetail(mProduct.Id);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mProduct.DetailList.addAll(rs);
				if (mProduct.DetailList.size() != 0) {
					mDetailAdapter.notifyDataSetChanged();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void NewComment() {
		if (!isProcessing) {
			new CallServiceTask() {
				int rs = 0;

				protected void onPreExecute() {
					isProcessing = true;
				};

				public void work() {
					try {
						rs = service.newComment(mProduct.Id, mContext.mUser.Id, mEdComment.getText().toString(), 1);
					} catch (Exception e) {
						rs = -1;
						e.printStackTrace();
					}
				};

				protected void onPostExecute(Void result) {
					isProcessing = false;
					if (rs < 1) {
						if (!mContext.isConnectionErrorShow) {
							mContext.isConnectionErrorShow = true;
							new ConnectionErrorDialog(mContext) {
								public void TryAgain() {
									NewComment();
								};
							}.show();
						}
					}
					if (rs > 0) {
						mFooter.RefreshComment();
						mEdComment.setText("");
						NotifyComment(rs);
					}
				};
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
	}

	private void NotifyComment(final int commentID) {
		new CallServiceTask() {
			public void work() {
				try {
					service.notifyComment(commentID, 1);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void Like() {
		if (!isProcessing) {
			if (mContext.mUser == null) {
				new OkCancelWarnningDialog(mContext, "You must login") {
					public void onOk() {
						Intent i = new Intent(mContext, LoginActivity.class);
						mContext.mDetailFragment.startActivityForResult(i, MainActivity.LOGINACTIVITY);
					};
				}.show();
			} else {
				if (mProduct.Liked()) {
					new OkCancelWarnningDialog(mContext, "Do you want to unlike this product?") {
						public void onOk() {
							new CallServiceTask() {
								private int rs = -2;

								protected void onPreExecute() {
									isProcessing = true;
								};

								public void work() {
									try {
										rs = service.newLike(mContext.mUser.Id, mProduct.Id, mProduct.Liked(), 1);
									} catch (Exception e) {
										e.printStackTrace();
									}
								};

								protected void onPostExecute(Void result) {
									if (rs == -2) {
										if (!mContext.isConnectionErrorShow) {
											mContext.isConnectionErrorShow = true;
											new ConnectionErrorDialog(mContext) {
												public void TryAgain() {
													Like();
												};
											}.show();
										}
										return;
									} else if (rs == -1) {
										mProduct.Likes = mProduct.Likes - 1;
										mTxtLike.setText(mProduct.Likes + "");
										mLayoutLikes.setBackgroundResource(R.drawable.like);
										mProduct.Liked = 0;
									} else {
										mTxtLike.setText(rs + "");
										mProduct.Likes = rs;
										mLayoutLikes.setBackgroundResource(R.drawable.like);
										mProduct.Liked = 0;
									}
									isProcessing = false;
								};
							}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
						};
					}.show();
				} else {
					new CallServiceTask() {
						private int rs = -2;

						protected void onPreExecute() {
							isProcessing = true;
						};

						public void work() {
							try {
								rs = service.newLike(mContext.mUser.Id, mProduct.Id, mProduct.Liked(), 1);
							} catch (Exception e) {
								e.printStackTrace();
							}
						};

						protected void onPostExecute(Void result) {
							if (rs == -2) {
								if (!mContext.isConnectionErrorShow) {
									mContext.isConnectionErrorShow = true;
									new ConnectionErrorDialog(mContext) {
										public void TryAgain() {
											Like();
										};
									}.show();
								}

							} else if (rs == -1) {
								mProduct.Likes = mProduct.Likes + 1;
								mTxtLike.setText(mProduct.Likes + "");
								mProduct.Liked = 1;
								mLayoutLikes.setBackgroundResource(R.drawable.liked);
							} else {
								mTxtLike.setText(rs + "");
								mProduct.Likes = rs;
								mLayoutLikes.setBackgroundResource(R.drawable.liked);
								mProduct.Liked = 1;
							}
							isProcessing = false;
						};
					}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEdComment.getWindowToken(), 0);

		switch (v.getId()) {
		case R.id.detail_btnSend:
			if (mEdComment.getText().length() != 0 && Utilities.checkComment(mEdComment.getText().toString())) {
				if (mContext.mUser == null) {
					Intent intent = new Intent(mContext, LoginActivity.class);
					mContext.startActivityForResult(intent, MainActivity.LOGINACTIVITY);
				} else
					NewComment();
			} else {
				mEdComment.setText("");
				new WarningDialog(mContext, mContext.getString(R.string.commentblank)).show();
			}
			break;

		case R.id.detail_layBtnLike:
			Like();
			break;

		}

	}

	public void RefreshLayout(final boolean stackTitle) {
		new CallServiceTask() {
			public void work() {
				int accountID = (mContext.mUser == null) ? -1 : mContext.mUser.Id;
				Log.w("NewProductDetail", "accountID: " + accountID + " || ProductID: " + mProduct.Id);
				try {
					mProduct = service.getProductByID(mProduct.Id, accountID);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
			};

			protected void onPostExecute(Void result) {
				if (mProduct == null) {
					mContext.onBackPressed();
					return;
				}
				if (mContext.getLocale().equals(Locale.ENGLISH))
					mTitle = mProduct.CategoryNameEN;
				else if (mContext.getLocale().equals(Locale.KOREA))
					mTitle = mProduct.CategoryNameKR;
				else
					mTitle = mProduct.CategoryNameVN;

				mTxtTitle.setText(mTitle);

				mDetailAdapter = new DetailAdapter(mContext, R.id.detail_listView, 0, mProduct);

				mListView.removeHeaderView(mHeader);
				mListView.removeFooterView(mRecommend);
				mListView.removeFooterView(mFooter);

				mHeader = new HeaderDetailView(mContext, mProduct);
				mFooter = new FooterDetailView(mContext, mProduct);
				mListView.addHeaderView(mHeader);

				mRecommend = new RecommendGroupView(mContext, mProduct);
				mListView.addFooterView(mRecommend);
				mListView.addFooterView(mFooter);

				mListView.setAdapter(mDetailAdapter);
				mBtnSend.setOnClickListener(NewProductDetailView.this);
				mLayoutLikes.setOnClickListener(NewProductDetailView.this);

				mTxtLike.setText(mProduct.Likes + "");
				Log.w("NewProductDetail", "Reload Liked: " + mProduct.Liked() + " " + mProduct.Liked);
				if (mProduct.Liked()) {
					mLayoutLikes.setBackgroundResource(R.drawable.liked);
				}
				if (mProduct.DetailList.size() == 0)
					GetDetail();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
}
